package com.example.lemis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lemis.common.exception.NotLoginException;
import com.example.lemis.common.utils.SessionUtils;
import com.example.lemis.model.domain.User;
import com.example.lemis.mapper.UserMapper;
import com.example.lemis.model.dto.PageDTO;
import com.example.lemis.model.dto.UserLoginRequest;
import com.example.lemis.model.dto.UserRegisterRequest;
import com.example.lemis.model.dto.passwordChangeDTO;
import com.example.lemis.model.vo.UserInfoVO;
import com.example.lemis.model.dto.resetPasswordDTO;
import com.example.lemis.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理审批用户 服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-06-24
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserInfoVO login(UserLoginRequest userIdentity) {
        String userTele = userIdentity.getTele();
        String userPassword = userIdentity.getPassword();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getTele, userTele);

        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return null; // 登录失败，返回 null
        }

        if (!passwordEncoder.matches(userPassword, user.getPassword())) {
            return null; // 密码不匹配，登录失败
        }
        // 转换为 UserVO
        UserInfoVO userInfo = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfo);   // 字段名 & 类型相同会自动复制

        SessionUtils.saveCurrentUserInfo(user);

        return userInfo;
    }

    /**
     * 描述：修改密码
     * @param pcDTO
     * @return
     */
    @Override
    public UserInfoVO password_change(passwordChangeDTO pcDTO) {
        User currentUser = SessionUtils.getCurrentUserInfo();
        if (currentUser == null) {
            return null; // 未登录或会话过期
        }

        userMapper.password_change(currentUser.getId(), passwordEncoder.encode(pcDTO.getNewPassword()));

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, currentUser.getId());
        User user = userMapper.selectOne(queryWrapper); // 返回修改后的用户

        UserInfoVO userInfo = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfo);
        return userInfo;

    }

    /**
     * 更新用户信息（名称、电话）
     * @param user
     * @return
     */
    @Override
    public User infoModify(User user) {
        User nowUser = SessionUtils.getCurrentUserInfo();
        if (nowUser == null) {
            return null;
        }
        userMapper.infoModify(user);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, user.getId());
        User u = userMapper.selectOne(queryWrapper);
        SessionUtils.saveCurrentUserInfo(u);
        return u;
    }


    @Override
    public void resetPassword(resetPasswordDTO rpdto) {
        rpdto.setNewPassword(passwordEncoder.encode(rpdto.getNewPassword()));
        userMapper.resetPassword(rpdto);
    }

    @Override
    public UserInfoVO auth() {
        User user = SessionUtils.getCurrentUserInfo();
        if (user == null) {
            throw new NotLoginException("您还未登录");
        }

        UserInfoVO userInfo = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfo); // 字段名 & 类型相同会自动复制
        return userInfo; // 返回当前管理员信息
    }

    @Override
    public Page<User> searchUserList(PageDTO pageDTO, String name) {
        Page<User> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        page = userMapper.searchUserList(page, name);
        return page;
    }

    @Override
    public User register(UserRegisterRequest user) {
        // 校验用户名和电话是否已存在
        if (userMapper.existsByUsername(user.getName())) {
            throw new IllegalArgumentException("用户名已存在");
        }
        System.out.println(user.getTele());
//        if (userMapper.existsByPhoneNumber(user.getTele())) {
//            throw new IllegalArgumentException("电话已存在");
//        }

        // 校验两次密码是否一致
        if (!user.getPassword().equals(user.getConfirmPassword())) {
            throw new IllegalArgumentException("两次输入的密码不一致");
        }

        // 密码加密
        String encodedPassword = passwordEncoder.encode(user.getPassword());

        // 创建用户信息对象并保存
        User use = new User();
        use.setTele(user.getTele());
        use.setName(user.getName());
        use.setPassword(encodedPassword);


        // 使用 MyBatis-Plus 插入数据
        System.out.println(use);
        userMapper.insertUserInfo(use);

        return use;
    }

    @Override
    public UserInfoVO deleteUser(User user) {
        userMapper.deleteUser(user);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, user.getId());
        User user1 = userMapper.selectOne(queryWrapper);
        // 不为空说明is_deleted字段设置出错
        if (user1 == null) {
            return null;
        }
        UserInfoVO userInfo = new UserInfoVO();
        BeanUtils.copyProperties(user1, userInfo);
        return userInfo;
    }

    @Override
    public User addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.addUser(user);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, user.getId());
        User user1 = userMapper.selectOne(queryWrapper);
        return user1;
    }
}
